package com.example.liuhb.broadcastreceiver;

import com.example.liuhb.broadcastreceiver.R;

import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    mBroadcastReceiver mBroadcastReceiver;
    MyBroadcastReceiver myBroadcastReceiver;
    Button btn;
    //动态注册广播
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=(Button)findViewById(R.id.btn);
        btn.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 1. 实例化BroadcastReceiver子类 & IntentFilter
        mBroadcastReceiver = new mBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        // 2. 设置接收广播的类型
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        // 3. 动态注册：调用Context的registerReceiver（）方法
        registerReceiver(mBroadcastReceiver, intentFilter);

        myBroadcastReceiver=new MyBroadcastReceiver();
        IntentFilter intentFilter1=new IntentFilter();
        intentFilter.addAction("com.example.liuhb.broadcastreceiver.MY_BROADCST");
        registerReceiver(myBroadcastReceiver, intentFilter1);
        System.out.println("-----------onResume-----------");
    }
    // 注册广播后，要在相应位置记得销毁广播
    // 即在onPause() 中unregisterReceiver(mBroadcastReceiver)
    // 当此Activity实例化时，会动态将MyBroadcastReceiver注册到系统中
    // 当此Activity销毁时，动态注册的MyBroadcastReceiver将不再接收到相应的广播。
    @Override
    protected void onPause() {
        super.onPause();
        //销毁在onResume()方法中的广播
        unregisterReceiver(mBroadcastReceiver);
        unregisterReceiver(myBroadcastReceiver);
        System.out.println("-----------onPause-----------");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn:
                System.out.println("-----------kkkk-----------");
                Intent intent=new Intent("com.example.liuhb.broadcastreceiver.MY_BROADCST");
                sendBroadcast(intent);
                break;
            default:
                break;
        }
    }
}
